package com.fer.andenginemvc.api;

import java.util.Collection;
import java.util.HashSet;

import org.andengine.engine.camera.Camera;
import org.andengine.engine.handler.IUpdateHandler;
import org.andengine.entity.scene.Scene;
import org.andengine.opengl.vbo.VertexBufferObjectManager;
import org.andengine.ui.activity.SimpleBaseGameActivity;

import com.fer.andenginemvc.api.gameObjects.GameObject;

import android.widget.Toast;

public abstract class Controller<T extends SimpleBaseGameActivity> implements IUpdateHandler{

	protected Scene scene;
	protected T baseGame;
	protected VertexBufferObjectManager vbom;
	protected Camera camera;
	
	private Collection<GameObject<?>> dieList;
	
	
	public Controller(Scene scene, T baseGame, Camera camera) {
		this.scene = scene;
		this.baseGame = baseGame;
		this.dieList = new HashSet<GameObject<?>>();
		this.scene.registerUpdateHandler(this);
		this.vbom = baseGame.getVertexBufferObjectManager();
		this.camera = camera;
	}
	
	public void addGameObject(GameObject<?> go)
	{
		scene.attachChild(go.entity);
	}
	
	public Scene getScene()
	{
		return scene;
	}
	
	public void onUpdate(float pSecondsElapsed)
	{
		for (GameObject<?> obj : dieList) {
			obj.die();
			scene.detachChild(obj.entity);
		}
		dieList.clear();
	};
	
	@Override
	public void reset() {};
	
	public void remove(GameObject<?> gameObject)
	{
		dieList.add(gameObject);
	}
	
	public void toast(final String message)
	{
		baseGame.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				Toast.makeText(baseGame, message, Toast.LENGTH_LONG).show();
			}
		});
	}
	
	/**
	 * This method is executed when a SceneManager displays the Controller
	 */
	public abstract void onShow();
	/**
	 * This method is executed when the scene is changed for another one.
	 */
	public void onLeave(){}; 
}
